package com.itgo.codegen.gen;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import com.itgo.codegen.bean.TemplateBean;
import com.itgo.codegen.util.TemplateUtil;

public abstract class AbstractGen {

	public void gen( String fileName , String templateName ){
		String content = render( build() , templateName ) ;
		if( content == null ){
			throw new IllegalArgumentException(" empty build content .") ;
		}
		BufferedWriter bwriter = null ;
		try{
			bwriter = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( fileName )) ) ;
			bwriter.write( content.toString() );
		}catch(Exception e){
			 e.printStackTrace();
		}finally{
			try{
				bwriter.flush();
				bwriter.close();
			}catch(Exception e){
				// Ignore ...
			}
		}
	}
	
	protected abstract TemplateBean build() ;
	
	protected String render( TemplateBean bean , String templateName ){
		return TemplateUtil.merge( templateName , bean ) ;
	}
}
